import { memo, useEffect, useState } from 'react'

import { Flex, DatePicker } from 'antd'

import './DataOperate.css'

import TrendNum from '@/views/components/TrendNum.tsx'

import deliver from '@/assets/home/deliver.png'

import project from '@/assets/home/project.png'

import service from '@/assets/home/service.png'

import table from '@/assets/home/table.png'

import plan from '@/assets/home/plan.png'

import CountUp from 'react-countup'

import DemandRight from './Demandright/Demandright'

import ServiceAssess from './Service/ServiceAssess'

import EchartsModule from '@/views/components/EchartsModule/index'

import { formatNumber } from '@/utils/formatNumber'

import { chartFontSize } from '@/utils/rem.ts'

import Mytable from '@/views/components/Mytable/index'

import React from 'react'

import { getHeadDemandOrder, getHeadProject, getdata_table_ranking, getArea_ranking, getDomain_distribute } from '@/api/DataOperate'

const { RangePicker } = DatePicker

const DataOperate: React.FC = () => {
  const [leftactive, leftsetActive] = useState('demand') //左边头部tabs

  const [rightactive, rightsetActive] = useState('count') //右边头部tabs

  const echartsRef = React.createRef()

  const DemandleftBottom = () => {
    const [datacount, setdatacount] = useState<any>([])

    const [data, setdata] = useState<any>([])

    const options = {
      title: {
        text: datacount,
        subtext: '总量/个',
        left: '20%',
        top: '60%',
        textAlign: 'center',
        itemGap: 6,
        textStyle: {
          fontSize: chartFontSize(28),
          color: '#2C2C2C',
          fontFamily: 'MicrosoftYaHei'
        },
        subtextStyle: {
          fontSize: chartFontSize(16),
          color: '#2C2C2C',
          fontFamily: 'MicrosoftYaHei'
        }
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        type: 'scroll',
        show: true,
        top: chartFontSize(143),
        itemGap: 16,
        right: chartFontSize(160),
        orient: 'vertical',
        icon: 'circle',
        textStyle: {
          rich: {
            name: {
              fontSize: chartFontSize(16),
              width: chartFontSize(177),
              color: '#57748B'
            },
            percent: {
              width: chartFontSize(93),
              fontSize: chartFontSize(16),
              align: 'right',
              color: '#32393F'
            },
            value: {
              fontSize: chartFontSize(16),
              align: 'right',
              color: '#32393F'
            }
          }
        },
        formatter(name: string) {
          return `{name|${name}} {percent|${data.find((item: any) => item?.name === name)?.percent ?? '-'} %} {value|${
            data.find((item: any) => item?.name === name)?.value ?? '-'
          }个} `
        }
      }
    }
    const seriesData: any = [
      {
        type: 'pie',
        radius: ['46%', '54%'],
        center: ['20%', '65%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 8
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: false,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]

    useEffect(() => {
      getDomain_distribute({
        time_min: time_min,
        time_max: time_max
      }).then((res: any) => {
        res.forEach((item: any) => {
          item.value = item.count
          item.name = item.domain.name
          item.percent = formatNumber(item.rate * 100)
          setdatacount((count: any) => Number((count += item.count)))
        })
        setdata(res)
      })
    }, [])
    return (
      <div className="w-100% h-500px">
        <EchartsModule onRef={echartsRef} options={options} seriesData={seriesData}></EchartsModule>
      </div>
    )
  }

  const countItems = [
    {
      label: '需求数',
      img: table,
      unit: '个',
      percent: false
    },
    {
      label: '交付需求',
      img: plan,
      unit: '次',
      percent: false
    },
    {
      label: '交付数据总量',
      img: deliver,
      unit: '万条',
      percent: false
    },
    {
      label: '服务项目数',
      img: project,
      unit: '个',
      percent: false
    },
    {
      label: '服务好评率',
      img: service,
      unit: '',
      percent: true
    }
  ]

  const dataTablecolumns = [
    { title: '排名', dataIndex: 'ranking', key: 'ranking', width: '109px' },

    {
      title: '数据表',
      dataIndex: 'table_name',
      key: 'table_name',
      ellipsis: true,
      render: (text: any) => <span style={{ color: '#2080F0' }}>{text}</span>
    },

    { title: '交付需求/个', dataIndex: 'delivered_count', key: 'delivered_count' }
  ]

  const [Tabledata, setTabledata] = useState([])

  const [dates, setDates] = useState<any>(null)

  const [time_min, settime_min] = useState('')

  const [time_max, settime_max] = useState('')

  const demandcolumns = [
    {
      title: '排名',
      dataIndex: 'ranking',
      key: 'ranking',
      width: '109px'
    },

    {
      title: '区域',
      dataIndex: 'area',
      key: 'area',
      ellipsis: true,
      render: (text: any) => <span style={{ color: '#2080F0' }}>{text}</span>
    },

    { title: '交付需求/个', dataIndex: 'count', key: 'count' }
  ]

  const [demanddata, setdemanddata] = useState([])

  const Tabs = (type: any, Typeof: any) => {
    if (Typeof === 'left') {
      leftsetActive(type)
    } else {
      if (type === 'count') {
        settime_min('')
        settime_max('')
        setDates(null)
      }
      rightsetActive(type)
    }
  }

  const DataProperHead = () => {
    const [headNum, setHeadNum] = useState<any>({
      需求数: {
        value: 0,
        monthValue: 0,
        weekValue: 0
      },
      交付需求: {
        value: 0,
        monthValue: 0,
        weekValue: 0
      },
      交付数据总量: {
        value: 0,
        monthValue: 0,
        weekValue: 0
      },
      服务项目数: {
        value: 0,
        monthValue: 0,
        weekValue: 0
      },
      服务好评率: {
        value: 0,
        monthValue: 0,
        weekValue: 0
      }
    })
    useEffect(() => {
      getHeadDemandOrder().then((res) => {
        setHeadNum((value: any) => ({
          ...value,
          需求数: {
            value: res.using_count.total,
            monthValue: res.using_count.month_week_growth.month,
            weekValue: res.using_count.month_week_growth.week
          },
          交付需求: {
            value: res.finished_count.total,
            monthValue: res.finished_count.month_week_growth.month,
            weekValue: res.finished_count.month_week_growth.week
          },
          交付数据总量: {
            value: res.finished_deliver_data_count.total,
            monthValue: res.finished_deliver_data_count.month_week_growth.month,
            weekValue: res.finished_deliver_data_count.month_week_growth.week
          },
          服务好评率: {
            value: res.positive_review_rate.total * 100,
            monthValue: res.positive_review_rate.month_week_growth.month,
            weekValue: res.positive_review_rate.month_week_growth.week
          }
        }))
      })
      getHeadProject().then((res) => {
        setHeadNum((value: any) => ({
          ...value,
          服务项目数: {
            value: res.total,
            monthValue: res.month_week_growth.month,
            weekValue: res.month_week_growth.week
          }
        }))
      })
    }, [])
    return (
      <div className="count-line">
        {countItems.map((it) => (
          <div className="count-item" key={it.label}>
            <img src={it.img} alt={it.label} />
            <div className="count-info">
              <div className="count-title">{it.unit ? `${it.label}/${it.unit}` : it.label}</div>
              <div className="count-num">
                <CountUp
                  end={it.unit === '万条' ? headNum[it.label].value / 10000 : headNum[it.label].value}
                  separator=","
                  decimals={it.percent ? 2 : 0}
                  suffix={it.percent ? '%' : ''}
                />
              </div>
              <div className="count-change">
                <TrendNum
                  label="本月"
                  value={it.unit === '万条' ? headNum[it.label].monthValue / 10000 : headNum[it.label].monthValue}
                  decimals={it.percent ? 2 : 0}
                  suffix={it.percent ? '%' : ''}
                />
              </div>
              <div className="count-change">
                <TrendNum
                  label="本周"
                  value={it.unit === '万条' ? headNum[it.label].weekValue / 10000 : headNum[it.label].weekValue}
                  decimals={it.percent ? 2 : 0}
                  suffix={it.percent ? '%' : ''}
                />
              </div>
            </div>
          </div>
        ))}
      </div>
    )
  }

  const DataProperTabs = () => {
    return (
      <Flex justify="space-between">
        <Flex className="leftItem">
          <span onClick={() => Tabs('demand', 'left')} className={leftactive === 'demand' ? 'active' : ''}>
            需求分析专题
          </span>
          <span onClick={() => Tabs('service', 'left')} className={leftactive === 'service' ? 'active' : ''}>
            服务质量专题
          </span>
        </Flex>
        <Flex align="center">
          <Flex className="rightItem">
            <span onClick={() => Tabs('count', 'right')} className={rightactive === 'count' ? 'active' : ''}>
              累计
            </span>
            <span className={rightactive === 'Time' ? 'active' : ''}>指定时间段</span>
          </Flex>
          <RangePicker value={dates} onChange={changeOn} className="mb-10px" size="middle"></RangePicker>
        </Flex>
      </Flex>
    )
  }

  const changeOn = (date: any, dateString: any) => {
    settime_min(dateString[0])
    settime_max(dateString[1])
    setDates(date)

    rightsetActive('Time')
  }

  useEffect(() => {
    getdata_table_ranking({
      time_min: time_min,
      time_max: time_max
    }).then((res) => {
      res.forEach((item: any, index: any) => {
        item.ranking = index + 1
        item.key = index + 1
      })
      setTabledata(res)
    })

    getArea_ranking({
      time_min: time_min,
      time_max: time_max
    }).then((res) => {
      res.forEach((item: any, index: any) => {
        item.ranking = index + 1
        item.key = index + 1
      })
      setdemanddata(res)
    })
  }, [time_min, time_max])

  return (
    <div className="dataProperty-page-wrapper">
      <DataProperHead />
      <div className="content">
        <DataProperTabs />
        {leftactive === 'demand' && (
          <div className="demandspecial-topic">
            <div className="left">
              <div className="flex">
                <div className="w-100% mr-46px" style={{ height: '554px' }}>
                  <div className="text-base font-bold pb-32px">热门数据表资源TOP10</div>
                  <Mytable columns={dataTablecolumns} data={Tabledata} />
                </div>
                <div className="mr-46px w-100%" style={{ height: '554px' }}>
                  <div className="text-base font-bold pb-32px">热门数据需求区域TOP10</div>
                  <Mytable columns={demandcolumns} data={demanddata} />
                </div>
              </div>
              <div>
                <div className="leftbbotm">热门数据需求领域分布</div>
                <DemandleftBottom />
              </div>
            </div>
            <div className="right">
              <DemandRight time_min={time_min} time_max={time_max} />
            </div>
          </div>
        )}
        {leftactive === 'service' && (
          <div className="servicespecial-topic">
            <ServiceAssess time_min={time_min} time_max={time_max} />
          </div>
        )}
      </div>
    </div>
  )
}
export default memo(DataOperate)
